<script setup lang="ts">
import { ref, shallowRef, onBeforeMount } from 'vue'
import { ElMessage as message } from 'element-plus'
import Add from './add.vue'
import Update from './update.vue'
import { useTableMixin } from '@/hooks/useTableMixin'
import { actionKeys } from '@/common/config'
import { getStatusTextByHRender } from '@/common/utils'
import { getUserPageApi, deleteUserApi, updateUserApi, getRolesInfoApi, giveRolesApi } from '@/api/user'
import { getRoleListApi, getSuccessStatus } from '@/api/role'

// 小于8列不建议每列都写列宽，写了可能导致撑不满布局100%。不写列宽表示自适应，自动补填剩余空间
const columns = shallowRef<TableColConfig[]>([
	{
		label: '复选框列',
		prop: 'selection',
		columnKey: 'selection',
		type: 'selection',
		// width: 55,
		fixed: 'left',
		align: 'center',
	},
	{
		label: '用户名',
		prop: 'username',
		columnKey: 'username',
		// width: 120,
		align: 'center',
	},
	{
		label: '状态',
		prop: 'status',
		columnKey: 'status',
		// width: 120,
		align: 'center',
		contentRender: ({ row }) => {
			return row.status ? getStatusTextByHRender('启用', 'success') : getStatusTextByHRender('禁用', 'danger')
		},
	},
	{
		label: '昵称',
		prop: 'name',
		columnKey: 'name',
		width: 150,
		align: 'center',
		showOverflowTooltip: true,
	},
	{
		label: '手机号',
		prop: 'phone',
		columnKey: 'phone',
		width: 150,
		align: 'center',
		showOverflowTooltip: true,
	},
	{
		label: '头像',
		prop: 'avatar',
		columnKey: 'avatar',
		// width: 120,
		align: 'center',
		showOverflowTooltip: true,
	},
	{
		label: '描述',
		prop: 'description',
		columnKey: 'description',
		width: 150,
		showOverflowTooltip: true,
		align: 'center',
	},
	{
		label: '最后登录时间',
		prop: 'lastLoginTime',
		columnKey: 'lastLoginTime',
		// width: 150,
		align: 'center',
		showOverflowTooltip: true,
	},
	{
		label: '操作',
		prop: 'operation',
		columnKey: 'operation',
		fixed: 'right',
		resizable: false,
		align: 'center',
		// width: 125,
	},
])
const roleSelectList = ref([])
const searchOptions = ref<SearchOptionType[]>([
	{ type: 'input', id: 'userName', props: { label: '用户名' } },
	{ type: 'input', id: 'nickName', props: { label: '昵称' } },
	{ type: 'input', id: 'description', props: { label: '描述' } },
	{
		type: 'select',
		id: 'status',
		props: { label: '状态' },
		innerComponentProps: {
			clearable: true,
			filterable: true,
			options: [
				{ label: '禁用', value: 0, disabled: false },
				{ label: '启用', value: 1, disabled: false },
			],
		},
	},
])
const giveRolesDialogVisible = ref(false)
const hasRoleIds = ref<IdType[]>([])
const noOperateIds=[1]
const isDisabled=(item:any)=>noOperateIds.includes(item.id)

const {
	basicPaginationConfig, // 表格分页基础配置
	current, // 当前页码
	size, // 页尺寸
	total, // 总条数
	addRef, // 新增组件ref
	updateRef, // 更新组件ref
	detailRef, // 详情组件ref
	filterOptions, // 查询条件
	getData, // 获取页数据的方法
	tableHeight, // 表格高度
	addDialogVisible, //新增对话框显示隐藏状态
	updateDialogVisible, //更新对话框显示隐藏状态
	tableList, // 表格数据
	selectedRows, // 选中行数据
	editRow, // 当前编辑数据
	fixedColWidth, // 固定列列宽
	handleSearchPanelcollapsed, //search-panel组件的 @collapsed 的处理函数
	handleSearch, // 搜索处理函数
	handleReset, // 重置表格数据处理函数
	handlePaginationChange, // 处理分页器变化处理函数
	handleColumnsChange, // 表头变化组件的处理函数
	handleAdd, // 点击新增按钮回调
	handleUpdate, // 点击更新按钮回调
	handleDelete, // 删除处理函数
	handleSelectedRowChange, // 表格选中行变化的回调
	handleImport, // 导入表格处理函数
	handleExport, // 导出表格数据处理函数
	handleAddCommit, // 新增提交
	handleUpdateCommit, // 更新提交
} = useTableMixin<UserType>({
	columns,
	listApiFunc: getUserPageApi,
	deleteApiFunc: deleteUserApi,
	actionList: [actionKeys.update, '1.3@@' + actionKeys.giveAuth, actionKeys.ban, actionKeys.delete],
	query_after: () => {},
	search_after: () => {},
})

onBeforeMount(() => {
	getRoleSelectList()
})

async function getRoleSelectList() {
	const res = await getRoleListApi()
	if (res.code == getSuccessStatus()) {
		roleSelectList.value = res.data.map((v: RoleType) => ({
			label: v.roleName,
			value: v.id,
		}))
		const item = searchOptions.value.find((v) => v.id == 'role')
		if (item) item.innerComponentProps!.options = roleSelectList.value
	}
}

async function handleBanChange(row: UserType) {
	const UpdateStatus = row.status ? 0 : 1
	const res = await updateUserApi([{ ...row, status: UpdateStatus }])
	if (res.code == getSuccessStatus()) {
		getData()
	}
}

async function handleGiveRoles(row: UserType) {
	editRow.value = row
	hasRoleIds.value = []
	giveRolesDialogVisible.value = true
	const res = await getRolesInfoApi(row.id)
	if (res.code == getSuccessStatus()) hasRoleIds.value = res.data?.map((v: RoleType) => v.id)
}

async function handleGiveRoleCommit() {
	const res = await giveRolesApi({ userId: editRow.value.id, roleIds: hasRoleIds.value })
	if (res.code == getSuccessStatus()) {
		giveRolesDialogVisible.value = false
		message.success('角色分配成功')
	}
}
</script>

<template>
	<div class="userManage">
		<search-panel :options="searchOptions" @collapsed="handleSearchPanelcollapsed" @reset="handleReset" @search="handleSearch" />
		<div class="my-table-tool">
			<div class="tool-left">
				<el-button type="primary" @click="handleExport" v-if="$hasAuth([actionKeys.export])">导出excel</el-button>
			</div>
			<div class="tool-right">
				<el-button type="primary" @click="handleAdd" v-if="$hasAuth([actionKeys.add])" style="margin-right: 5px">新增用户</el-button>
				<set-table-columns :list="columns" @confirm="handleColumnsChange" />
			</div>
		</div>

		<my-table
			ref="tableRef"
			border
			stripe
			:data="tableList"
			:columns="columns"
			style="width: 100%"
			class="myTable"
			rowKey="id"
			:maxHeight="tableHeight"
			@selection-change="handleSelectedRowChange"
			:pagination="{ ...basicPaginationConfig, current, size, total }"
		>
			<template #operation="{ row }">
				<el-button type="primary" size="small" @click="handleUpdate(row)" v-if="$hasAuth([actionKeys.update])">修改</el-button>
				<el-button :disabled="isDisabled(row)" type="primary" size="small" @click="handleGiveRoles(row)" v-if="$hasAuth([actionKeys.giveAuth])">分配角色</el-button>

				<el-popconfirm
					:title="`确定要${row.status ? '禁用' : '解除禁用'}吗?`"
					confirm-button-text="确定"
					cancel-button-text="取消"
					@confirm="handleBanChange(row)"
					v-if="$hasAuth([actionKeys.delete])"
				>
					<template #reference><el-button  :disabled="isDisabled(row)" danger size="small">{{ row.status ? '禁用' : '启用' }}</el-button></template>
				</el-popconfirm>

				<el-popconfirm title="确定要删除吗?" confirm-button-text="确定" cancel-button-text="取消" @confirm="handleDelete(row)" v-if="$hasAuth([actionKeys.delete])">
					<template #reference><el-button :disabled="isDisabled(row)" type="danger" size="small">删除</el-button></template>
				</el-popconfirm>
			</template>
		</my-table>

		<el-dialog v-model="addDialogVisible" title="新增用户" width="80%" :modal="false" draggable :close-on-click-modal="false" align-center>
			<el-scrollbar :maxHeight="$getDialogBodyMaxHeight()">
				<div style="padding: 0 10px">
					<Add ref="addRef" />
				</div>
			</el-scrollbar>
			<template #footer>
				<div class="dialog-footer" style="display: flex; justify-content: flex-end">
					<el-button @click="addDialogVisible = false">取消</el-button>
					<el-button type="primary" @click="handleAddCommit">确定</el-button>
				</div>
			</template>
		</el-dialog>

		<el-dialog v-model="updateDialogVisible" title="更新用户" width="80%" :modal="false" draggable :close-on-click-modal="false" align-center>
			<el-scrollbar :maxHeight="$getDialogBodyMaxHeight()">
				<div style="padding: 0 10px">
					<Update :editRow="editRow" ref="updateRef" />
				</div>
			</el-scrollbar>
			<template #footer>
				<div class="dialog-footer" style="display: flex; justify-content: flex-end">
					<el-button @click="updateDialogVisible = false">取消</el-button>
					<el-button :disabled="isDisabled(editRow)" type="primary" @click="handleUpdateCommit">确定</el-button>
				</div>
			</template>
		</el-dialog>

		<el-dialog v-model="giveRolesDialogVisible" title="分配角色" width="50%" :modal="false" draggable :close-on-click-modal="false" align-center>
			<div style="padding: 0 10px">
				<my-select style="width: 100%" multiple v-model="hasRoleIds" placeholder="请为用户选择角色" :options="roleSelectList" :filterable="true" clearable />
			</div>
			<template #footer>
				<div class="dialog-footer" style="display: flex; justify-content: flex-end">
					<el-button @click="giveRolesDialogVisible = false">取消</el-button>
					<el-button type="primary" @click="handleGiveRoleCommit">确定</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<style scoped lang="scss"></style>
